//
//  WmcWatermarkModel.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/3/29.
//

import AMapSearchKit
import CoreLocation
import Foundation
import YPBedrock
import YPNetwork

// MARK: - [WmcWatermarkDetailModel]

open class WmcWatermarkDetailModel: NSObject, YPNetworkJsonProtocol {
    // Lifecycle

    override public required init() {
        super.init()
    }

    // Open

    /// 标签，用于外部标记，不属于水印模型内部使用的字段
    open var stringTag: String = ""

    /// 分类id
    open var classifyId: Int = 0

    /// 水印名称
    open var name: String = ""

    /// 透明度 0-100
    open var alpha: Int = 0

    /// 默认大小  0-100
    open var size: Int = 0

    /// 是否可添加到相册  1：可以   0：不可以
    open var supportAlbum: Bool = false

    /// 模板预览图
    open var templateImg: String = ""

    /// 模板id
    open var templateId: Int = 0

    /// 水印字段
    open var fields: [WmcWatermarkOptionModel] = []

    /// 图标
    open var icon: String = ""

    /// 水印id （对应wmc_type）
    open var wmId: Int = 0

    /// 水印id （兼容安卓）
    open var wm_id: Int = 0

    // MARK: 静态数据

    /// 静态数据
    open var staticData: StaticData = .init()

    override open var description: String {
        #if DEBUG
            var fieldsStr = ""
            fields.forEach { option in
                let optionStr =
                    """
                    =====================水印字段====================
                    类型:\(option.fieldType)
                    \"\(option.title)\": \"\(option.content)\"
                    是否开启:\(option.isOpen)|可否操作:\(option.isAction)
                    可否编辑标题:\(option.enableEditTitle)|可否编辑内容:\(option.enableEditContent)
                    背景色：\(option.bgColor)|字色:\(option.textColor)
                    """
                fieldsStr.append(optionStr)
            }
            let des =
                """
                -------水印信息--------
                [\(name)]
                水印id：\(wmId)|模版类型:\(templateType)
                透明度：\(alpha)|大小:\(size)
                \(fieldsStr)
                ----------------------
                """
            return des
        #else
            return ""
        #endif
    }

    // Public

    /// 空水印实例化方法
    public static var EmptyWatermark: WmcWatermarkDetailModel {
        return .init()
    }

    /// 定位信息（非服务端返回，本地构建的字段）
    /// 主要用于序列化键值对
    public var location: Location = .init()

    /// 判断是否包含某个字段
    public func containsField(with label: String) -> Bool {
        for field in fields {
            if field.label == label {
                return true
            }
        }
        return false
    }

    /// 通过Label获取field字段
    public func getField(with label: String) -> WmcWatermarkOptionModel? {
        for field in fields {
            if field.label == label {
                return field
            }
        }
        return nil
    }

    /// 通过label移除某个字段
    public func removeField(with label: String) {
        var newFields = fields
        for (idx, field) in fields.enumerated() {
            if field.label == label {
                newFields.remove(at: idx)
            }
        }
        fields = newFields
    }

    public func mapping(mapper: HelpingMapper) {
        mapper <<< self.alpha <-- "opacity"
        mapper <<< self.templateImg <-- "img"
        mapper <<< self.templateId <-- "styleCode"

        mapper >>> self.stringTag
        mapper >>> self.staticData
    }

    public func didFinishMapping() {
        compatibleAndroidFields()
    }

    // Internal

    /// 产品让加的，目的是用户提交的自定义地址时想看到真实的地址信息，但是如果用户关闭了定位权限或者网络，这个字段会没有数据
    var position: Location = .init()

    /// 如果给安卓分享的水印字段，需要在这里处理兼容
    func shareCompatibleAndroidFields() {
        if wm_id == 0 { // ⚠️反向解析安卓的数据给我使用
            wm_id = wmId // ⚠️反向解析安卓这个作为id
        }
        for field in fields { // ⚠️反向解析userOpen是安卓的自定义字段，需要兼容
            if field.isOpen {
                field.userOpen = 1
            } else {
                field.userOpen = 0
            }
        }
    }

    /// 如果是安卓传过来的水印字段，需要在这里处理兼容
    func compatibleAndroidFields() {
        if wmId == 0 { // ⚠️正向解析安卓的数据给我使用
            wmId = wm_id // ⚠️安卓版本可能会返回这个作为id
        }
        for field in fields {
            if let userOpen = field.userOpen { // ⚠️userOpen是安卓的自定义字段，需要兼容
                if userOpen == 1 {
                    field.isOpen = true
                } else if userOpen == 0 {
                    field.isOpen = false
                }
            }
        }
    }

    /// 构建定位信息（非服务端返回，本地构建的字段）
    func createLocationInfo() {
        let location: WmcWatermarkDetailModel.Location = .init()
        if let poi = WmcLocationManager.shared.poiStatus.value?.data?.poi,
           let addressPrefix = WmcLocationManager.shared.addressPrefix
        {
            location.address = poi.name ?? ""
            location.cityName = poi.city ?? ""
            location.district = addressPrefix
            if let point = poi.location {
                location.latitude = "\(point.latitude)"
                location.longitude = "\(point.longitude)"
            }
            self.location = location
        }
    }

    // Fileprivate

    /// 日志系统
    fileprivate func log(_ log: String) {
        WmcLogManager.DebugLog(type: .watermarkDetailModel, log: log)
    }
}

// MARK: 开放扩展

public extension WmcWatermarkDetailModel {
    class StaticData: NSObject {
        // Open

        /// 拍摄时的地理信息
        open var staticLocation: CLLocation?

        /// 逆地理编码
        open var staticReGeocode: AMapReGeocode?

        /// 拍摄时的方位角信息
        open var staticAzimuth: Double?

        /// 拍摄时的天气信息
        open var staticWeater: WmcWeatherModel?

        /// 拍摄时的地址信息
        open var staticAddress: WmcSelectAddressModel?

        /// 拍摄时的地址信息（渲染使用）
        open var drawStaticAddress: WmcSelectAddressModel?

        /// 静态时间信息
        open var staticDate: Date?

        // MARK: 静态地址选择需要

        /// 地址前缀信息列表
        open var staticAddressPrefixList: [String]?

        /// 地址前缀信息
        open var staticAddressPrefix: String?

        /// pio数据列表
        open var staticPioList: [WmcSelectAddressModel]?

        // Internal

        /// 锁定当前数据
        /// 可以用于静态渲染
        func saveStaticInformation() {
            staticLocation = WmcLocationManager.shared.locationStatus.value?.data?.location
            staticReGeocode = WmcLocationManager.shared.locationStatus.value?.data?.reGeocode
            staticAzimuth = WmcCLLocationManager.shared.azimuthAngleRelay.value
            staticWeater = WmcWeatherManager.share.weather.value
            staticAddress = WmcLocationManager.shared.poiStatus.value?.data
            drawStaticAddress = WmcLocationManager.shared.poiStatus.value?.data
            staticDate = WmcDateManager.shared.networkDate.value
            staticAddressPrefixList = WmcLocationManager.shared.getAddressPrefixList()
            staticAddressPrefix = WmcLocationManager.shared.addressPrefix
            staticPioList = WmcLocationManager.shared.poiList.value
        }
    }

    /// 锁定当前数据
    /// 可以用于静态渲染
    func saveStaticInformation() {
        staticData.saveStaticInformation()
    }

    /// 拷贝静态数据
    func copyStaticInformation(with model: WmcWatermarkDetailModel) {
        staticData = model.staticData
    }

    /// 拷贝静态数据
    func copyStaticData(with data: StaticData) {
        staticData = data
    }
}

public extension WmcWatermarkDetailModel {
    /// 水印模版类型
    enum TemplateType: Int, CaseIterable {
        /// 无水印
        case empty = 0
        /// 工程记录,项目巡检,会议记录,施工前中后,材料进场
        case project = 1
        /// 记工水印
        case recordWork = 2
        /// 考勤打卡水印
        case clocking = 3
        /// 装修施工水印
        case fitment = 4
        /// 疫情防控水印
        case epidemic = 5
        /// 时间地点水印
        case timeAddress = 6
        /// 标题蒙版水印
        case titleMask = 7
        /// 时间日历模板
        case calendarIcon = 8
        /// 验收模板
        case acceptance = 9
        /// 治安巡逻 安保水印
        case security = 10
        /// 环卫模板
        case sanitation = 11
        /// 电子时钟模板
        case electronicClock = 12
        /// 天气模板
        case weather = 13
        /// 地点模板模板
        case address = 14
        /// 防盗全屏模板
        case guardTheft = 15
        /// 图标模板、消毒记录模板
        case icon = 16
        /// 隔离记录模板
        case isolation = 17
        /// 工作汇报模板
        case office = 18
        /// 酒店管理模板
        case hotel = 19
        /// 环境治理模板
        case environment = 20
        /// 促销模板
        case promotion = 21

        /// 未知
        case unknown

        struct Info {}
    }

    /// 模版类型
    var templateType: TemplateType {
        return .init(rawValue: templateId) ?? .unknown
    }
}

public extension WmcWatermarkDetailModel {
    enum Size: CaseIterable {
        /// 特小
        case superSmall
        /// 小
        case small
        /// 推荐默认
        case `default`
        /// 大
        case big
        /// 特大
        case superBig

        struct Info {
            /// 实际缩放值
            var scale: CGFloat
            /// 标题
            var title: String
            /// 指示器上进度等级
            var progress: CGFloat
        }

        var info: Info {
            switch self {
            case .superSmall: return .init(scale: 0.6, title: "特小", progress: 0)
            case .small: return .init(scale: 0.8, title: "较小", progress: 0.25)
            case .`default`: return .init(scale: 1, title: "推荐", progress: 0.5)
            case .big: return .init(scale: 1.1, title: "中等", progress: 0.75)
            case .superBig: return .init(scale: 1.3, title: "特大", progress: 1)
            }
        }

        /// 实例化
        init(rawValue: Int) {
            switch rawValue {
            case 0: self = .superSmall
            case 25: self = .small
            case 50: self = .`default`
            case 75: self = .big
            case 100: self = .superBig
            default: self = .`default`
            }
        }
    }

    /// 缩放大小
    var scaleSize: Size {
        return .init(rawValue: size)
    }
}

public extension WmcWatermarkDetailModel {
    /// 复制模型
    func copyModel() -> Self? {
        guard let dic = toJSON(),
              let model = Self.deserialize(from: dic) else { return nil }
        model.copyStaticInformation(with: self) // 静态数据一起复制
        return model
    }

    /// 拷贝用户编辑过的参数
    func copyUserEditValue(with model: WmcWatermarkDetailModel) {
        // field赋值
        for field in fields {
            for userField in model.fields {
                if field.fieldId == userField.fieldId { // 字段匹配
                    log("开始复制用户数据到水印\(field.fieldType)|\(field.title)=====")
                    if field.cacheHash() == userField.cacheHash() { // 比较相等。表无变化，使用用户数据
                        field.title = userField.title
                        field.content = userField.content
                        field.isOpen = userField.isOpen
                        field.brandAttribute = userField.brandAttribute
                        log("复制成功")
                    } else {
                        log("复制失败")
                    }
                    log("完成复制~~~")
                }
            }
        }
        // 透明度与大小
        alpha = model.alpha
        size = model.size
    }
}

// MARK: 非开放

public extension WmcWatermarkDetailModel {
    class Location: NSObject, YPNetworkJsonProtocol {
        // Lifecycle

        override public required init() {
            super.init()
        }

        // Public

        /// 地址
        public var address: String = ""

        /// 城市
        public var cityName: String = ""

        /// 区域
        public var district: String = ""

        /// 纬度
        public var latitude: String = ""

        /// 经度
        public var longitude: String = ""
    }
}

extension WmcWatermarkDetailModel {
    /// 获取品牌图属性对象
    func optionBrand() -> WmcWatermarkOptionModel? {
        var optionBrand: WmcWatermarkOptionModel?
        fields.enumerated().forEach { (idx, option) in
            if option.fieldType == .brand {
                optionBrand = option
            }
        }
        guard let optionBrand = optionBrand else { return nil }
        return optionBrand
    }
}

extension WmcWatermarkDetailModel {
    /// 默认过滤项，用于统计标题文字数量
    var defaultFieldTitleFilters: [WmcWatermarkOptionModel.FieldType] {
        return [.brand]
    }

    /// 所有标题最大字数
    var fieldTitleMaxCount: Int {
        return fieldTitleMaxCount()
    }

    /// 所有标题最大字数
    func fieldTitleMaxCount(filters: [WmcWatermarkOptionModel.FieldType] = []) -> Int {
        var maxTitleCount = 0
        fields.forEach { option in
            if defaultFieldTitleFilters.contains(option.fieldType) == false,
               filters.contains(option.fieldType) == false
            {
                if option.isOpen {
                    let count = option.title.count
                    if count > maxTitleCount {
                        maxTitleCount = count
                    }
                }
            }
        }
        return maxTitleCount
    }

    /// 创建水印模板
    func createTemplateView(styleMode: WmcBaseWatermarkTemplateView.StyleMode = .dynamicDraw,
                            showCertification: Bool = true) -> WmcBaseWatermarkTemplateView?
    {
        var templateView: WmcBaseWatermarkTemplateView?
        // 选择模板创建不同视图
        switch templateType { // 模板id值
        case .empty: // 无水印
            templateView = WmcEmptyTemplateView()
        case .project: // 工程记录,项目巡检,会议记录,施工前中后,材料进场
            templateView = WmcProjectTemplateView()
        case .recordWork: // 记工水印
            templateView = WmcRecordWorkTemplateView()
        case .clocking: // 考勤打卡水印
            templateView = WmcClockingTemplateView()
        case .fitment: // 装修施工水印
            templateView = WmcFitmentTemplateView()
        case .epidemic: // 疫情防控水印
            templateView = WmcEpidemicTemplateView()
        case .timeAddress: // 时间地点水印
            templateView = WmcTimeAddressTemplateView()
        case .titleMask: // 标题蒙版水印
            templateView = WmcTitleMaskTemplateView()
        case .calendarIcon: // 时间日历模板
            templateView = WmcCalendarIconTemplateView()
        case .acceptance: // 验收模板
            templateView = WmcAcceptanceTemplateView()
        case .security: // 治安巡逻 安保水印
            templateView = WmcSecurityTemplateView()
        case .sanitation: // 环卫模板
            templateView = WmcSanitationTemplateView()
        case .electronicClock: // 电子时钟模板
            templateView = WmcElectronicClockTemplateView()
        case .weather: // 天气模板
            templateView = WmcWeatherTemplateView()
        case .address: // 地点模板模板
            templateView = WmcAddressTemplateView()
        case .guardTheft: // 防盗全屏模板
            templateView = WmcGuardTheftTemplateView()
        case .icon: // 图标模板、消毒记录模板
            templateView = WmcIconTemplateView()
        case .isolation: // 隔离记录模板
            templateView = WmcIsolationTemplateView()
        case .office: // 工作汇报模板
            templateView = WmcOfficeTemplateView()
        case .hotel: // 酒店管理模板
            templateView = WmcHotelTemplateView()
        case .environment: // 环境治理模板
            templateView = WmcEnvironmentTemplateView()
        case .promotion: // 促销模板
            templateView = WmcPromotionTemplateView()

        case .unknown: // 未知
            templateView = WmcVersionTemplateView()
        }
        guard let templateView = templateView else {
            log("水印类型设置失败！请检查模板是否符合！")
            return nil
        }
        templateView.styleMode = styleMode
        templateView.isShowCertificationWatermark = showCertification
        templateView.makeConstraints()
        return templateView
    }
}
